package com.willian.andrappfw.ui;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import androidx.annotation.Nullable;

import com.willian.andrappfw.R;
import com.willian.andrappfw.utils.WPreferenceManager;

public class SettingItemView extends LinearLayout {
    TextView name;
    ToggleButton toggle;

    public SettingItemView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    public SettingItemView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    void init(Context context, AttributeSet attr) {
        LayoutInflater.from(context).inflate(R.layout.item_setting, this);
        name = findViewById(R.id.textView_name);
        toggle = findViewById(R.id.toggle);

        if (attr != null) {
            TypedArray ta = context.obtainStyledAttributes(attr, R.styleable.SettingItemView);
            String settingName = ta.getString(R.styleable.SettingItemView_setting_name);
            ta.recycle();
            name.setText(settingName);
            toggle.setChecked(WPreferenceManager.getInstance().getBoolean(settingName, true));
            toggle.setOnCheckedChangeListener((buttonView, isChecked) ->
                    WPreferenceManager.getInstance().edit().putBoolean(settingName, toggle.isChecked()).apply()
            );
            toggle.setClickable(false);
            setOnClickListener(v -> toggle.setChecked(!toggle.isChecked()));
        }
    }
}
